import datetime
import os
import sys

# 将工程目录加入包扫描
currPath = os.path.abspath(os.path.dirname(__file__))
srcPath = os.path.split(currPath)[0]
rootPath = os.path.split(srcPath)[0]
projectPath = os.path.split(rootPath)[0]
sys.path.append(projectPath)

from typing import List
from src.tasks.enterprise.EntEnterprise import EntEnterprise
from src.utils import CommonUtils


class SyncEnterpriseNameList:
    def __init__(self, logger, localDb, dcdb):
        self.logger = logger
        self.localDb = localDb
        self.dcdb = dcdb

    # # 抽取最新主体名单
    def __queryEnterpriseV2__(self):
        sql = """
            SELECT e.*, t.name as type_code_name, s.name as score_type_name FROM enterprise_info_v2 e
            INNER JOIN enterprise_used_for u ON e.credit_code = u.credit_code 
            LEFT JOIN base_enterprise_type t ON t.code = e.type_code 
            LEFT JOIN enterprise_type_score s ON s.value = e.score_type
            WHERE u.scenario_id = 2 AND u.used = 1   
        """
        return self.dcdb.Query(sql)

    def __queryLocal__(self):
        sql = """
        select id,comp_code,enterprise_name,credit_code,create_time,update_time 
        from ent_enterprise 
        """
        return self.localDb.Query(sql)

    # 入口
    def getEnterpriseList(self) -> List[EntEnterprise]:

        # 抽取最新名单
        self.logger.info("加载 主体名单")
        remoteDatas = self.__queryEnterpriseV2__()
        remoteDatas = {d["credit_code"]: d for d in remoteDatas}
        self.logger.info("加载 主体名单：%d" % len(remoteDatas))

        # 抽取本地名单
        self.logger.info("加载 本地主体名单")
        localDatas = self.__queryLocal__()
        localDatas = {d["credit_code"]: d for d in localDatas}
        self.logger.info("加载 本地主体名单：%d" % len(localDatas))

        now = datetime.datetime.now()

        # 检查新增数据
        newCompKeys = remoteDatas.keys() - localDatas.keys()
        insertDatas = []
        # 提取新增主体
        for k, v in remoteDatas.items():
            if newCompKeys.__contains__(k):
                ent = EntEnterprise()
                ent.comp_code = v["comp_code"]
                ent.credit_code = v["credit_code"]
                ent.enterprise_name = v["name"]
                ent.ent_type = v["type_code"]
                ent.ent_type_sub = v["type_code_sub"]
                ent.nature = v["custom_nature_code"]
                ent.srm_trade_type = v["custom_industry_l2"]
                ent.srm_trade_type_superior = v["custom_industry_l1"]
                ent.ccx_industry_code = v["score_type"]
                ent.trade_type = v["score_type_name"]
                ent.classify_type = 0
                ent.create_time = now
                ent.update_time =now
                ent.delete_flag = 0
                insertDatas.append(ent)
        self.logger.info("新增主体：%d" % len(insertDatas))

        # 提取更新主体
        sameCodes = list(remoteDatas.keys() & localDatas.keys())
        updateDatas = []
        for code in sameCodes:
            remoteData = remoteDatas.get(code)
            d = localDatas[code]
            ent = EntEnterprise()
            ent.id = d["id"]
            ent.comp_code = remoteData["comp_code"]
            ent.credit_code = remoteData["credit_code"]
            ent.enterprise_name = remoteData["name"]
            ent.ent_type = remoteData["type_code"]
            ent.ent_type_sub = remoteData["type_code_sub"]
            ent.nature = remoteData["custom_nature_code"]
            ent.srm_trade_type = remoteData["custom_industry_l2"]
            ent.srm_trade_type_superior = remoteData["custom_industry_l1"]
            ent.ccx_industry_code = remoteData["score_type"]
            ent.trade_type = remoteData["score_type_name"]
            ent.create_time = d["create_time"]
            ent.update_time = now
            ent.classify_type = 0
            ent.delete_flag = 0
            updateDatas.append(ent)
        self.logger.info("更新主体：%d" % len(updateDatas))

        # 提取已删除企业
        deletedCodes = list(localDatas.keys() - remoteDatas.keys())
        self.logger.info("无效企业：%d" % len(deletedCodes))

        del remoteDatas
        del newCompKeys
        del localDatas
        del sameCodes
        # 合并数据并返回
        retList = []
        retList.extend(insertDatas)
        retList.extend(updateDatas)

        return retList, deletedCodes
